package com.example.commons.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 自动扫描 业务消息处理器并注册为Bean
 */
@Slf4j
@Component
public class HandlerRegister extends ApplicationObjectSupport {

    /**
     * 自定义业务消息处理器
     */
    private final static Map<String, AbstractMsgHandler> HANDLERS_MAP = new HashMap<>();

    @Override
    protected void initApplicationContext(ApplicationContext context) throws BeansException {
        super.initApplicationContext(context);
        Map<String, Object> handlerBeans = context.getBeansWithAnnotation(MsgHandler.class);
        handlerBeans.keySet().forEach(beanName -> {
            Object bean = handlerBeans.get(beanName);
            Class clazz = bean.getClass();
            if (bean instanceof AbstractMsgHandler && clazz.getAnnotation(MsgHandler.class) != null) {
                MsgHandler taskHandler = (MsgHandler) clazz.getAnnotation(MsgHandler.class);
                String value = taskHandler.value();
                if (HANDLERS_MAP.keySet().contains(value)) {
                    throw new RuntimeException("MsgHandler has Exits. value=" + value);
                }
                HANDLERS_MAP.put(taskHandler.value(), (AbstractMsgHandler) handlerBeans.get(beanName));
                log.info("MsgHandler Register. value={}, beanName={}", taskHandler.value(), beanName);
            }
        });
    }

    public static AbstractMsgHandler getHandler(String cmd) {
        return HANDLERS_MAP.get(cmd);
    }
}